package com.airpi.activities;

import java.util.ArrayList;
import java.util.Arrays;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.airpi.R;
import com.airpi.heavy_tasks.AsyncTaskFragment;

/**
 * Users
 * @author galilee
 *
 */
public class MainLeftFragment extends Fragment implements Observer {

	//Initialisation of the two List Views (User List and Media List)
	private ListView listUserView;
	private ArrayAdapter<String> listViewAdapter;
	private ArrayList<String> userList;

	/**
	 * Getter and Setter of the User List
	 * The setter is also used to set the user List View content in the UI 
	 * 
	 */
	public void setUserList(String[] usList){
		System.out.println("SET USER LIST");
		String[] itemsUser = usList;
		userList = new ArrayList<String>(Arrays.asList(itemsUser));
		FragmentActivity frag = getActivity();
		if(frag != null){
			System.out.println("Mise a jour UserList");
			listViewAdapter = new ArrayAdapter<String>(frag, android.R.layout.simple_list_item_1, userList);
			if(listUserView!=null){
				listUserView.setAdapter(listViewAdapter);
			}
		}
	}

	/**
	 * Method called on the generation of the main UI view, handling the different fragments
	 * On generation of the View, it inflates the layout of the different tabs
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView;
		rootView = inflater.inflate(R.layout.main_user_list, container, false);
		listUserView = (ListView)rootView.findViewById(R.id.main_user_listview);
		if(listUserView != null)listUserView.setAdapter(this.listViewAdapter);

		new Thread() {
			private AsyncTaskFragment atc;
			private Fragment f;

			public Thread set(Fragment f) {
				this.f = f;
				return this;
			}
			
			@Override
			public void run() {
				while(true) {
					try {
						atc = new AsyncTaskFragment(((Observer)f), "UserList");
						atc.execute();
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.set(this).start();

		return rootView;
	}

	@Override
	public void notifier(String s) {
		System.out.println("result = " + s);
		if(s.contains("UserList")){
			String [] res = s.substring(19).split(";");
			this.setUserList(res);
		}
	}
}